package base.day02;

import java.util.Arrays;

/**
 * 描述：
 * 荷兰国旗问题
 *
 * @author hl
 * @version 1.0
 * @date 2020/10/24 9:27
 */
public class NetherlandsFlag {

    public static void main(String[] args) {
        int[] arr = {2, 6, 8, 4, 4, 1, 3, 9, 6, 8};
        int[] partition = partition(arr, 0, arr.length - 1, 4);
        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(partition));
    }

    /**
     * 将小于num的放左边，将等于num的放中间，大于num的放右边
     *
     * @param arr
     * @param l
     * @param r
     * @param num
     * @return
     */
    public static int[] partition(int[] arr, int l, int r, int num) {
        int less = l - 1;
        int more = r + 1;
        while (l < more) {
            if (arr[l] < num) {
                swap(arr, ++less, l++);
            } else if (arr[l] > num) {
                swap(arr, l, --more);
            } else {//==num
                l++;
            }
        }
        return new int[]{less + 1, more - 1};//返回等于num的序列的范围
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}
